//
//  PhotoCVPresenter.swift
//  NewDelivery
//
//  Created by 天下宅 on 2016/11/9.
//  Copyright © 2016年 天下宅. All rights reserved.
//

import UIKit

class PhotoCVPresenter: BaseCVPresenter,UIImagePickerControllerDelegate,UINavigationControllerDelegate {
    
    weak var hintLabel:UILabel?

    
    
    var takePhotoVC:UIImagePickerController = {
        let vc = UIImagePickerController()
        vc.sourceType = .camera
        vc.allowsEditing = true
        return vc
    }()
    
    init(_ cv: UICollectionView, cvc: BaseVC, label:UILabel? = nil) {
        hintLabel = label
        super.init(cv, cvc: cvc)
    }
    
    convenience init(WithCV cv: UICollectionView, cvc: BaseVC, label:UILabel? = nil) {
        self.init(cv, cvc: cvc , label:label)
        self.setupCollectionView()
        
        let lp = UILongPressGestureRecognizer.init(target: self, action: #selector(longPressToDo(gesture:)))
        self.collectionView.addGestureRecognizer(lp)
        lp.delaysTouchesBegan = true
        

    }
    
    
    override var contents: [Any]?
    {
        didSet{
            var i = 1
            for data in contents! {
                let image = data as! UIImage
                image.wk_index = "\(i)"
                i += 1
            }
        }
    }
    var selectImages =  [UIImage]()
    {
        didSet{
            hintLabel?.text = "已选择\(self.selectImages.count)/\(self.maxCount)张图片"
        }
    }
    var maxCount = 1
    static let cellID = "PhotoCell"
    
    
    override func setupCollectionView() {
        
        collectionView.register(PhotoCVCell.self, forCellWithReuseIdentifier: PhotoCVPresenter.cellID)
        
        WKPhotoManager.shared.refreshData { (images) in
            self.contents = images
            super.setupCollectionView()
        }
    }
    
    override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: PhotoCVPresenter.cellID, for: indexPath) as! PhotoCVCell
        
        if indexPath.row == 0
        {
            cell.status = .none
        }
        else
        {
            let image = self.contents![indexPath.row - 1] as! UIImage
            cell.status = .optional
            cell.image = image
            for img in selectImages {
                if image.wk_isEqualImageTo(img)
                {
                    cell.status = .selected
                    break
                }
            }
        }
        return cell
    }
    
    override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        let cell = collectionView.cellForItem(at: indexPath) as! PhotoCVCell
        switch cell.status {
        case .none:
            takePhotoVC.delegate = self
            self.vc.present(takePhotoVC, animated: true, completion: nil)
        case .optional:
            cell.status = .selected
            if selectImages.count >= maxCount
            {
                
                //可能有多个源
                let oldImage = selectImages.remove(at: 0)
                
                var flag = false
                for data in self.contents! {
                    let image = data as! UIImage
                    if image.wk_isEqualImageTo(oldImage)
                    {
                        flag = true
                        break
                    }
                }
                
                if flag
                {
                    let path = IndexPath.init(row: Int(oldImage.wk_index!)!, section: indexPath.section)
                    let thisCell = collectionView.cellForItem(at: path ) as! PhotoCVCell
                    thisCell.status = .optional
                }
            
            }
            self.selectImages.append(self.contents![indexPath.row - 1] as! UIImage)
            
            
        case .selected:
            cell.status = .optional
            
            var index = 0
            for tempImage in self.selectImages {
                if tempImage.wk_isEqualImageTo(cell.image!)
                {
                    index = self.selectImages.index(of: tempImage)!
                    break
                }
            }
           self.selectImages.remove(at: index)
            hintLabel?.text = "已选择\(self.selectImages.count)/\(self.maxCount)张图片"

        }
    }
    
    func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
        self.takePhotoVC.dismiss(animated: true, completion: nil)
    }
    
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
        let image = info["UIImagePickerControllerOriginalImage"] as! UIImage
        WKPhotoManager.shared.sava(image: image, block: {(img) in
            if self.selectImages.count >= self.maxCount
            {
                let oldImage = self.selectImages.remove(at: 0)
                let path = IndexPath.init(row: Int(oldImage.wk_index!)!, section: 0)
                let thisCell = self.collectionView.cellForItem(at: path ) as! PhotoCVCell
                thisCell.status = .optional
                
                for img in self.selectImages
                {
                    img.wk_index = "\(UInt(img.wk_index!)! + 1)"
                }
            }
            self.selectImages.append(img)
            self.hintLabel?.text = "已选择\(self.selectImages.count)/\(self.maxCount)张图片"
            WKPhotoManager.shared.refreshData { (images) in
                self.contents = images
                super.setupCollectionView()
            }
        })
        self.takePhotoVC.dismiss(animated: true, completion: nil)
    }

    
    func longPressToDo(gesture:UILongPressGestureRecognizer)  {
        if gesture.state != .began
        {
            return
        }
        
        let p = gesture.location(in: collectionView)
        if let indexPath = self.collectionView.indexPathForItem(at: p)
        {
            let cell = self.collectionView.cellForItem(at: indexPath) as! PhotoCVCell
            if cell.status != .none
            {
                
                
                WKPhotoManager.shared.getSourceImage(WithImage: cell.image!, block: { (img) in
                    let ppvc = self.vc as! WKPhotoPickerVC
                    ppvc.displayShowView(img)
                })
            }
            
        }
        
    }
    
}
